//
//  XZWeatherController.m
//  生活小助手
//
//  Created by lixiangzhou on 14-8-7.
//  Copyright (c) 2014年 lxz. All rights reserved.
//
#define futureW 80

#import "XZWeatherController.h"
#import "AFNetworking.h"
#import "XZFunctionKey.h"
#import "MBProgressHUD+MJ.h"
#import "XZWeatherFutureView.h"
#import "MJExtension.h"
#import "XZWeather.h"
#import "XZWeatherIcon.h"
#import <CoreLocation/CoreLocation.h>
#import <AddressBook/AddressBook.h>

@interface XZWeatherController ()<UIAlertViewDelegate,CLLocationManagerDelegate>

@property (weak,nonatomic) UIView *topView;

@property (weak,nonatomic) UILabel *bigTempLabel;

@property (weak,nonatomic) UIButton *cityBtn;

@property (weak,nonatomic) UILabel  *cityLable;

@property (weak,nonatomic) UIImageView *weatherImage;

@property (weak,nonatomic) XZWeatherFutureView *today;

@property (weak,nonatomic) XZWeatherFutureView *tomorrow;

@property (weak,nonatomic) XZWeatherFutureView *tomtom;

@property (weak,nonatomic) XZWeatherFutureView *bigtom;

@property (weak,nonatomic) UILabel *dressLabel;

@property (weak,nonatomic) UILabel *windLabel;

@property (weak,nonatomic) UILabel *comfortLabel;

/**定位**/
@property (strong,nonatomic) CLLocationManager *locationMgr;

/**当前的 位置**/
@property (strong,nonatomic) CLLocation *currentLocation;

@end

@implementation XZWeatherController
- (CLLocationManager *)locationMgr
{
    if (!_locationMgr) {
        _locationMgr = [[CLLocationManager alloc]init];
        _locationMgr.delegate = self;
        _locationMgr.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        _locationMgr.distanceFilter = 1000.f;
    }
    return _locationMgr;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.view.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.locationMgr;
    
    /**上面的视图**/
    UIView *topView  = [[UIView alloc]init];
    topView.backgroundColor = DColor(176, 117, 173);
    topView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight * .7f);
    [self.view addSubview:topView];
    self.topView = topView;
    
    UILabel *bigTempLabel = [self setupLabelWithText:@"28°"];
    bigTempLabel.frame = topView.bounds;
    bigTempLabel.font = [UIFont systemFontOfSize:110];
    bigTempLabel.textAlignment = NSTextAlignmentCenter;
    [topView addSubview:bigTempLabel];
    self.bigTempLabel = bigTempLabel;
    
    UIButton *cityBtn = [[UIButton alloc]init];
    [cityBtn setTitle:@"设置" forState:UIControlStateNormal];
    cityBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    cityBtn.titleLabel.textColor = [UIColor whiteColor];
    [cityBtn addTarget:self action:@selector(cityChangeOnClcik:) forControlEvents:UIControlEventTouchUpInside];
    cityBtn.frame = CGRectMake(kScreenWidth - 90, 20, 90, 30);
    [topView addSubview:cityBtn];
    self.cityBtn = cityBtn;
    
    UIButton *back = [[UIButton alloc]init];
    [back setTitle:@"返回" forState:UIControlStateNormal];
    back.titleLabel.font = [UIFont systemFontOfSize:15];
    back.titleLabel.textColor = [UIColor whiteColor];
    [back addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    back.frame = CGRectMake(20, 20, 30, 30);
    [topView addSubview:back];
    
    /**大号的天气图标**/
    UIImageView *weatherImage = [[UIImageView alloc]init];
    weatherImage.centerX = kScreenWidth * .5f;
    weatherImage.x = kScreenWidth / 4;
    weatherImage.y = 40;
    weatherImage.width = kScreenWidth /4;
    weatherImage.height = weatherImage.width;
    //    weatherImage.frame = CGRectMake(90, 40, 140, 80);
    weatherImage.image = [UIImage imageNamed:@"fine"];
    weatherImage.contentMode = UIViewContentModeScaleAspectFit;
    [topView addSubview:weatherImage];
    self.weatherImage = weatherImage;
    
    //    UILabel *cityLable = [[UILabel alloc]init];
    UILabel *cityLable = [self setupLabelWithText:@"北京"];
    //    cityLable.backgroundColor = [UIColor redColor];
    cityLable.x= kScreenWidth / 2;
    cityLable.y = 40;
    cityLable.width = kScreenWidth / 4;
    cityLable.height = cityLable.width;
    cityLable.font = [UIFont systemFontOfSize:40];
    //    cityLable.textAlignment = NSTextAlignmentCenter;
    [topView addSubview:cityLable];
    self.cityLable = cityLable;
    
    /**显示今天天气具体信息*/
    UIView *topInforView = [[UIView alloc]init];
    topInforView.frame = CGRectMake(0, 240, kScreenWidth - 2 * kMargin, kScreenHeight * 0.1875);
    [topView addSubview:topInforView];
    
    UILabel *windLabel = [self setupLabelWithText:@"东北风3-4级转小于3级"];
    windLabel.font =[UIFont systemFontOfSize:13];
    windLabel.frame = CGRectMake(kMargin, 0, topInforView.width, topInforView.height / 3);
    [topInforView addSubview:windLabel];
    self.windLabel = windLabel;
    
    UILabel *comfortLabel = [self setupLabelWithText:@"较舒适,适宜锻炼,非常干燥"];
    comfortLabel.font =[UIFont systemFontOfSize:13];
    comfortLabel.frame = CGRectMake(kMargin,  CGRectGetMaxY(windLabel.frame), topInforView.width, topInforView.height / 3);
    [topInforView addSubview:comfortLabel];
    self.comfortLabel = comfortLabel;
    
    UILabel *dressLabel = [self setupLabelWithText:@"天气热，建议着短裙、短裤、短薄外套、T恤等夏季服装"];
    dressLabel.font =[UIFont systemFontOfSize:13];
    dressLabel.frame = CGRectMake(windLabel.x, CGRectGetMaxY(comfortLabel.frame), windLabel.width, windLabel.height + kMargin);
    [topInforView addSubview:dressLabel];
    self.dressLabel = dressLabel;
    
    
    /**底部视图**/
    UIView *bottomFutureView = [[UIView alloc]init];
    bottomFutureView.backgroundColor = DColor(207, 150, 196);
    bottomFutureView.frame = CGRectMake(0,CGRectGetMaxY(topView.frame), kScreenWidth, kScreenHeight * .3f);
    [self.view addSubview:bottomFutureView];
    
    XZWeatherFutureView *today = [[XZWeatherFutureView alloc]init];
    today.backgroundColor = DColor(207, 150, 196);
    today.frame = CGRectMake(0, 0, futureW, bottomFutureView.height);
    [bottomFutureView addSubview:today];
    self.today = today;
    
    XZWeatherFutureView *tomorrow = [[XZWeatherFutureView alloc]init];
    tomorrow.backgroundColor = DColor(199, 134, 188);
    tomorrow.frame = CGRectMake(futureW, 0, futureW, bottomFutureView.height);
    [bottomFutureView addSubview:tomorrow];
    self.tomorrow = tomorrow;
    
    XZWeatherFutureView *tomtom = [[XZWeatherFutureView alloc]init];
    tomtom.backgroundColor = DColor(188, 110, 173);
    tomtom.frame = CGRectMake(futureW * 2, 0, futureW, bottomFutureView.height);
    [bottomFutureView addSubview:tomtom];
    self.tomtom = tomtom;
    
    XZWeatherFutureView *bigtom = [[XZWeatherFutureView alloc]init];
    bigtom.backgroundColor = DColor(171, 93, 164);
    bigtom.frame = CGRectMake(futureW * 3, 0, futureW, bottomFutureView.height);
    [bottomFutureView addSubview:bigtom];
    self.bigtom = bigtom;
    
    [self searchWeather];
    
    // 👍手势
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
    [self.view addGestureRecognizer:pan];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.locationMgr startUpdatingLocation];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.locationMgr stopUpdatingLocation];
}
- (void)pan:(UIPanGestureRecognizer *)pan
{
    CGPoint point = [pan translationInView:self.view];
    if (point.x < 100) return;
    [self backClick];
        
}

-(UILabel *)setupLabelWithText:(NSString *)text
{
    UILabel *label = [[UILabel alloc]init];
    label.text = text;
    label.backgroundColor = [UIColor clearColor];
    label.font =[UIFont systemFontOfSize:13];
    label.textColor = [UIColor whiteColor];
    label.numberOfLines = 0;
    return label;
}
- (void)backClick
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)cityChangeOnClcik:(UIButton *)btn
{
    
    UIAlertView *cityAlter = [[UIAlertView alloc]initWithTitle:@"修改城市" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    cityAlter.alertViewStyle = UIAlertViewStylePlainTextInput;
    [cityAlter textFieldAtIndex:0].text = self.cityLable.text;
    [cityAlter show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex!=1) return;
    NSLog(@"alertView == %@",[alertView textFieldAtIndex:0].text);
    self.cityLable.text  = [alertView textFieldAtIndex:0].text ;
    [self searchWeather];
    
}
#pragma mark Core Location委托方法用于实现位置的更新
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = [locations lastObject];
    
    self.currentLocation = location;
    
    [self reverseGeocodeWith:location];
}
/**
 *  定位反编码,返回当前的城市
 */
- (void)reverseGeocodeWith:(CLLocation *)location
{
   CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        if ([placemarks count] > 0) {
            
            CLPlacemark *placemark = placemarks[0];
            
            NSDictionary *addressDictionary =  placemark.addressDictionary;
            
//            NSString *address = [addressDictionary objectForKey:(NSString *)kABPersonAddressStreetKey];
            
            NSString *city = [addressDictionary objectForKey:(NSString *)kABPersonAddressCityKey];
            city = city == nil ? @"" : city;
            NSLog(@"当前所在的城市：=== %@",city);
            
            NSString *state = [addressDictionary objectForKey:(NSString *)kABPersonAddressStateKey];
            state = state == nil ? @"" : state;
            NSLog(@"当前所在的城市：=== %@",state);
//            self.cityLable.text = city;
            if ([city isEqualToString:@""]) {
                self.cityLable.text = [state stringByReplacingOccurrencesOfString:@"市" withString:@""];
            }
            else
            {
            self.cityLable.text = [city stringByReplacingOccurrencesOfString:@"市" withString:@""];
            }
            
            
            NSLog(@"当前所在的城市：=== %@",state);
            [self searchWeather];
        }
    }];
    
}

- (UIStatusBarStyle) preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
/**
 *  根据城市查找天气
 */
- (void)searchWeather
{
    if (self.cityLable.text.length > 0) {
        [MBProgressHUD showMessage:@"正在查询..."];
        //http://v.juhe.cn/weather/index?cityname=阜阳&key=d2247b101c5d72ec3a2c6a9bcc8092f3
        NSString *baseUrl = @"http://v.juhe.cn/weather/index";
        
        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
        
        NSMutableDictionary *mD = [NSMutableDictionary dictionary];
        mD[@"cityname"] = self.cityLable.text;
        mD[@"key"] = [XZFunctionKey weatherKey];
        
        [mgr GET:baseUrl parameters:mD success:^(AFHTTPRequestOperation *operation, NSDictionary  *responseObject) {
            
            [MBProgressHUD hideHUD];

            if (responseObject.count == 0) {
                
                [MBProgressHUD showError:@"网络错误"];
            }
            NSString *resultCode = responseObject[@"resultcode"];
            NSString *reason = responseObject[@"reason"];
            if (![resultCode isEqualToString:@"200"]) {
                [MBProgressHUD showError:reason];
                return ;
            }
            /**result**/
            NSDictionary *result = responseObject[@"result"];
            
            /**当前的天气状态**/
            NSDictionary *sk = result[@"sk"];
            /**今天的详细天气**/
            __block NSDictionary *today =  result[@"today"];
            /**未来几天的天气情况**/
            NSDictionary *future = result[@"future"];
            
            /**设置大号温度的label**/
            NSString *bigTemp = [NSString stringWithFormat:@"%@°",sk[@"temp"]];
            self.bigTempLabel.text = bigTemp;
            
            /**设置大号天气图片**/
            self.weatherImage.image = [XZWeatherIcon weatherIconWithWeatherId:today[@"weather_id"]];
            
            /**设置今天的天气信息情况**/
            self.windLabel.text = [NSString stringWithFormat:@"风:%@,湿度:%@",today[@"wind"],sk[@"humidity"]];
            self.comfortLabel.text = [NSString stringWithFormat:@"舒适度:%@,户外:%@,干燥:%@",today[@"comfort_index"],today[@"exercise_index"],today[@"drying_index"]];
            self.dressLabel.text = today[@"dressing_advice"];
            
            
            /**遍历字典把未来几天的天气字典存入数组**/
            NSMutableArray *weatherDictArry = [NSMutableArray array];
            [future  enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                [weatherDictArry addObject:obj];
            }];
            /**把未来几天的天气转成模型**/
            NSArray *weathers = [XZWeather objectArrayWithKeyValuesArray:weatherDictArry];
            
            // 把天气重新排序
            int sortCount = 0;
            for (int i = 0; i < weathers.count; i++) {
                XZWeather *weather = weathers[i];
                if ([weather.week isEqualToString:today[@"week"]]) {
                    sortCount = i;
                    break;
                }
            }
            NSMutableArray *weatherM = [NSMutableArray arrayWithArray:weathers];
            for (int i = 0; i < sortCount; i++) {
                XZWeather *weather = weathers[i];
                [weatherM removeObjectAtIndex:0];
                [weatherM insertObject:weather atIndex:weatherM.count];
            }
     
            weathers = weatherM;
            /**设置未来几天的天气情况**/
            self.today.weather = weathers[0] ;
            self.tomorrow.weather = weathers[1];
            self.tomtom.weather = weathers[2];
            self.bigtom.weather = weathers[3];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"网络错误"];
            NSLog(@"%@",error);
        }];
        
       }
}
@end
